<template>
    <div class="layout-padding">
        <splitpanes>
            <pane size="47">
                <div class="layout-padding-auto layout-padding-view">
                    <!--查询表单-->
                    <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">

                        <el-form-item :label="$t('edijob.creationTime')" prop="creationTime">
                            <div class="block">
                                <el-date-picker v-model="creationTime" :clearable="false" type="daterange" unlink-panels
                                    range-separator="To" start-placeholder="Start date" end-placeholder="End date"
                                    :shortcuts="shortcuts" />
                            </div>
                        </el-form-item>

                        <el-form-item label="JobID" prop="jobid" style="width: 200px;">
                            <el-input v-model="state.queryForm.jobid" clearable placeholder="jobid" />
                        </el-form-item>

                        <el-form-item :label="$t('edijob.jobType')" prop="jobType">
                            <el-select v-model="state.queryForm.jobType" filterable clearable clear-icon="CloseBold">
                                <el-option v-for="item in optionsjobType" :key="item.value" :label="item.text"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>

                        <el-form-item :label="$t('edijob.jobStatus')" prop="jobStatus" style="width: 240px;">
                            <el-select v-model="state.queryForm.jobStatus">
                                <el-option v-for="item in optionsjobStatus" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>

                        <el-form-item :label="$t('edijob.isAutoExcute')" prop="isAutoExcute" style="width: 240px;">
                            <el-select v-model="state.queryForm.isAutoExcute">
                                <el-option v-for="item in optionsisAutoExecute" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>

                        <el-form-item>
                            <el-button icon="el-icon-search" type="primary"  @click="dataquery">{{ $t('edijob.query')}}</el-button>
                            <el-button icon="refresh"  @click="resetQuery">{{ $t('edijob.reset') }}</el-button>
                            <el-button icon="el-icon-delete" type="danger" @click="handleDelete(selectObjs)">{{
                                $t('edijob.delete') }}</el-button>
                        </el-form-item>

                        <el-form-item>
                            <el-dropdown>
                                    <el-button type="primary">
                                        {{ $t('edijob.operation') }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
                                    </el-button>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item icon="CloseBold" @click="jobMethod(selectObjs,'jobStop')">{{ $t('edijob.jobStop') }}</el-dropdown-item>
                                            <el-dropdown-item icon="Select" @click="jobMethod(selectObjs,'jobRecover')">{{ $t('edijob.jobRecover') }}</el-dropdown-item>
                                            <el-dropdown-item icon="Promotion" @click="jobMethod(selectObjs,'jobOneExcute')">{{ $t('edijob.jobOneExcute') }}</el-dropdown-item>
                                            <el-dropdown-item icon="RefreshRight" @click="jobMethod(selectObjs,'jobReset')">{{ $t('edijob.jobReset') }}</el-dropdown-item>
                                          <el-dropdown-item icon="FolderDelete"
                                                            @click="jobMethod(selectObjs,'clearRedisReport')">
                                            {{ $t('edijob.clearRedisReport') }}
                                          </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </el-form-item>

                    </el-form>
                    <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle" style="width: 100%;height: 100%"
                        :header-cell-style="tableStyle.headerCellStyle" @row-click="clickRow" stripe
                        @sort-change="sortChangeHandle" @selection-change="selectionChangeHandle">
                        <el-table-column type="selection" width="40" align="center" />
                        <el-table-column type="index" label="#" width="50" />
                        <el-table-column prop="id" label="JobID"  width='80'/>
                        <el-table-column prop="jobCompleteStatus" :label="$t('edijob.jobStatus')" width='85'>
                            <template #default="scope">
                                <!--根据不同的状态选择不同的颜色的tag-->
                                <el-tag size="large" :type="scope.row.jobCompleteStatus === 'isSubmit' ? 'success' : 'danger'">
                                {{ scope.row.jobCompleteStatus === 'isSubmit' ? $t('edijob.isSubmit') : $t('edijob.notSubmit')}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="jobName" :label="$t('edijob.jobName')"  width='180'/>
                      <el-table-column prop="materialCode" :label="$t('edijob.materialCode')" width='120'/>
                        <el-table-column prop="creationTime" :label="$t('edijob.creationTime')"  width='170'/>
                        <el-table-column prop="isAutoExcute" :label="$t('edijob.isAutoExcute')" width='90'>
                            <template #default="scope">
                                <!--根据不同的状态选择不同的颜色的tag-->
                                <el-tag size="large" :type="scope.row.isAutoExcute === 'Y' ? '' : 'warning'">
                                {{ scope.row.isAutoExcute === 'Y' ? $t('edijob.yes') : $t('edijob.no') }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="executeTimes" :label="$t('edijob.executeTimes')" width='85' />
                        <!-- <el-table-column :label="$t('edijob.operation')" width="140">
                            <template #default="scope">
                                <el-button icon="edit-pen" text type="primary" v-auth="'platform_basDicSet_edit'"
                                    @click="processFormDialogRef.openEditDialog(scope.row)">{{ $t('edijob.edit') }}
                                </el-button>
                                <el-button icon="delete" type="primary" text @click="handleDelete([scope.row.id])">
                                    {{ $t('edijob.delete') }}
                                </el-button>
                            </template>
                        </el-table-column> -->
                    </el-table>
                    <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                        v-bind="state.pagination" />
                </div>
            </pane>
            <pane size="53">
                <div class="layout-padding-auto layout-padding-view">
                    <jobDetail ref="dataFormRef"></jobDetail>
                </div>
            </pane>
        </splitpanes>
    </div>
</template>

<script setup lang="ts">
import {BasicTableProps, useTable} from "/@/hooks/table";
import {useMessage, useMessageBox} from "/@/hooks/message";
import {deleteJob, getAllJobType, getJobList, updateJob} from "/@/api/platform/edi/job";
import jobDetail from "/@/views/edi/job/jobDetail.vue"
import {useI18n} from 'vue-i18n';

const { t } = useI18n();

const processFormDialogRef = ref()

//job类型
const optionsjobType = ref([])
onMounted(() => {
    getAllJobType().then(res => {
        optionsjobType.value = res.data
    })
})

//job状态
const optionsjobStatus = [
    {
        value: 'All',
        label: t('edijob.all'),
    },
    {
        value: 'isSubmit',
        label: t('edijob.isSubmit'),
    },
    {
        value: 'notSubmit',
        label: t('edijob.notSubmit'),
    },
]

//是否自动提交
const optionsisAutoExecute = [
    {
        value: 'All',
        label: t('edijob.all'),
    },
    {
        value: 'Y',
        label: t('edijob.yes'),
    },
    {
        value: 'N',
        label: t('edijob.no'),
    },
]

// 搜索变量
const queryRef = ref()
const dataFormRef = ref();

const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate()-1); // 今天之后的6天，总共一周
let creationTime = ref([endDate, today]);

const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            return [start, end];
        },
    },
];
const getYMD = (date: any) => {
    // 获取年份
    const year = date.getFullYear();

    // 获取月份，注意JavaScript中的月份是从0开始的，因此需要+1
    const month = String(date.getMonth() + 1).padStart(2, '0');

    // 获取日期
    const day = String(date.getDate()).padStart(2, '0');

    // 拼接成 yyyy-MM-dd 格式的字符串
    const formattedDate = `${year}-${month}-${day}`;

    return formattedDate;
};
const dataquery = () => {
    state.queryForm.StartTime = creationTime.value ? getYMD(creationTime.value[0]) : '';
    state.queryForm.EndTime = creationTime.value ? getYMD(creationTime.value[1]) : '';
    getDataList();
};

//左边查询job
const state: BasicTableProps = reactive<BasicTableProps>({
    queryForm: {
        StartTime: creationTime.value ? getYMD(creationTime.value[0]) : '',
        EndTime: creationTime.value ? getYMD(creationTime.value[1]) : '',
    },
    pageList: getJobList
})

state.queryForm.isAutoExcute='All'
state.queryForm.jobStatus='All'
// 点击行的时候触发
const clickRow = (row: any) => {
    dataFormRef.value.refresh(row)
}

const {
    getDataList,
    currentChangeHandle,
    sizeChangeHandle,
    sortChangeHandle,
    downBlobFile,
    tableStyle
} = useTable(state)

// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
// 多选事件
const selectionChangeHandle = (objs: { id: string }[]) => {
    selectObjs.value = objs.map(({ id }) => id);
    multiple.value = !objs.length;
};

//job执行停止
const jobMethod = async (ids: Array<number>,jobMethodtype:string) => {
  if (ids?.length === 0 && jobMethodtype != "clearRedisReport") {
        return useMessage().error(t('edijob.selectJob'))
    }
  const idArray: IdArray = ids?.map(item => (item));
    try {
        await updateJob({
            jobid: idArray,
            updateJobType:jobMethodtype
        })
        getDataList();
        useMessage().success(t('edijob.executeSuccess'));
    } catch (err: any) {
        useMessage().error(t('edijob.executeFail') + err.msg)
    }
}


// 删除操作
const handleDelete = async (ids: Array<number>) => {
    if (ids?.length === 0) {
        return useMessage().warning(t('edijob.selectJob'))
    }

    const idArray: IdArray = ids.map(item => (item));

    useMessageBox().confirm(t('edijob.permanentlyDeleted')).then(async () => {
        try {
            await deleteJob({
                jobid: idArray
            })
            getDataList();
            useMessage().success(t('edijob.deleteSuccess'));
        } catch (err: any) {
            useMessage().error(t('edijob.deleteFaild') + err.msg)
        }
    })
};

// 清空搜索条件
const resetQuery = () => {
    // 清空搜索条件
    queryRef.value?.resetFields()
		state.queryForm.StartTime=''
		state.queryForm.EndTime=''
	creationTime.value=[]
    getDataList(false)
}
</script>
